package com.abel.bigwater.dataserver.model.qdies

import com.abel.bigwater.data.BcdString
import com.abel.bigwater.dataserver.model.PacketCmdException
import io.netty.buffer.ByteBuf
import org.joda.time.DateTime

class DtenAskStateData : D10BaseData(6 + 2 + 20) {
    override var type = FuncType.AskState

    var timeBcd: BcdString? = null

    var voltBcd: BcdString? = null

    var warnBcd: BcdString? = null

    var time: DateTime? = null
        get() = if (timeBcd == null) null else
            DateTime(timeBcd?.bcdArray!![0] + DateTime.now().year / 100 * 100,
                    timeBcd?.bcdArray!![1].toInt(),
                    timeBcd?.bcdArray!![2].toInt(),
                    timeBcd?.bcdArray!![3].toInt(),
                    timeBcd?.bcdArray!![4].toInt(),
                    timeBcd?.bcdArray!![5].toInt())
        set(value) {
            field = value
            timeBcd = if (value != null) {
                BcdString(byteArrayOf(value?.year.rem(100).toByte(),
                        value.monthOfYear.toByte(),
                        value.dayOfMonth.toByte(),
                        value.hourOfDay.toByte(),
                        value.minuteOfHour.toByte(),
                        value.secondOfMinute.toByte()), true)
            } else null
        }

    var volt: Float? = null
        get() = if (voltBcd == null) null else
            voltBcd?.bcdArray!![0].toFloat() + voltBcd?.bcdArray!![1] / 100.0F
        set(value) {
            field = value
            voltBcd = if (field != null)
                BcdString(byteArrayOf(field!!.toByte(), field!!.times(100).rem(100).toByte()), true)
            else null
        }

    override fun fill(buf: ByteBuf) {
        assert(time != null && volt != null && warnBcd?.size == 20)

        buf.writeBytes(timeBcd!!.hexArray).writeBytes(voltBcd!!.hexArray).writeBytes(warnBcd!!.hexArray)
    }

    override fun parse(buf: ByteBuf): Boolean {
        buf.apply {
            if (readableBytes() != len) throw PacketCmdException("not enough bytes for ask-state")
            timeBcd = BcdString.create(this, 6)
            voltBcd = BcdString.create(this, 2)
            warnBcd = BcdString.create(this, 20)
        }
        assert(time != null && volt != null && warnBcd?.size == 20)

        return true
    }

    override fun count(): Int = len
}